<template>
  <div class="reports-container">
    <div class="header">
      <h2>统计报表</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        >
        </el-date-picker>
        <el-button type="primary" @click="refreshData" icon="el-icon-refresh">刷新数据</el-button>
      </div>
    </div>
    
    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon primary">
              <i class="el-icon-monitor"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ serverCount }}</div>
              <div class="stat-label">服务器总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon success">
              <i class="el-icon-position"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ totalMigrations }}</div>
              <div class="stat-label">总迁移次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon warning">
              <i class="el-icon-warning-outline"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ failedMigrations }}</div>
              <div class="stat-label">失败迁移</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon info">
              <i class="el-icon-document"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ logCount }}</div>
              <div class="stat-label">操作日志</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 用户统计概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#90939920', color: '#909399' }">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.totalUsers || 0 }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#67C23A20', color: '#67C23A' }">
              <i class="el-icon-user-solid"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.onlineUsers || 0 }}</div>
              <div class="stat-label">在线用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#E6A23C20', color: '#E6A23C' }">
              <i class="el-icon-circle-plus"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ userStats.newUsers || 0 }}</div>
              <div class="stat-label">新增用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: '#409EFF20', color: '#409EFF' }">
              <i class="el-icon-star-off"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ userGrowthRate }}%</div>
              <div class="stat-label">用户增长率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>迁移任务状态统计</span>
          </div>
          <div class="chart-container">
            <div ref="statusChart" class="chart-placeholder"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>服务器操作系统分布</span>
          </div>
          <div class="chart-container">
            <div ref="osChart" class="chart-placeholder"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>迁移任务趋势</span>
          </div>
          <div class="chart-container">
            <div ref="trendChart" class="chart-placeholder"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 用户增长趋势 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24">
        <el-card class="chart-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>用户增长趋势</span>
          </div>
          <div class="chart-container">
            <div ref="userGrowthChart" class="chart-placeholder"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import * as echarts from 'echarts'

export default {
  name: 'Reports',
  data() {
    return {
      dateRange: [],
      statusChart: null,
      osChart: null,
      trendChart: null,
      userGrowthChart: null,
      userStats: {
        totalUsers: 0,
        onlineUsers: 0,
        newUsers: 0
      }
    }
  },
  computed: {
    // 重新定义计算属性，避免与data中的属性冲突
    serverList() {
      return this.$store.state.servers.servers || []
    },
    taskList() {
      return this.$store.state.migrations.tasks || []
    },
    logList() {
      return this.$store.state.logs.logs || []
    },
    userList() {
      return this.$store.state.users.users || []
    },
    serverCount() {
      return (this.serverList || []).length
    },
    totalMigrations() {
      return (this.taskList || []).length
    },
    failedMigrations() {
      return (this.taskList || []).filter(task => task.status === 'FAILED').length
    },
    logCount() {
      return (this.logList || []).length
    }
  },
  async created() {
    await this.loadData()
  },
  mounted() {
    this.initCharts()
  },
  beforeDestroy() {
    if (this.statusChart) {
      this.statusChart.dispose()
    }
    if (this.osChart) {
      this.osChart.dispose()
    }
    if (this.trendChart) {
      this.trendChart.dispose()
    }
    if (this.userGrowthChart) {
      this.userGrowthChart.dispose()
    }
  },
  methods: {
    ...mapActions('servers', ['fetchServers']),
    ...mapActions('migrations', ['fetchTasks']),
    ...mapActions('logs', ['fetchLogs']),
    ...mapActions('users', ['fetchUserStats', 'fetchUsers']),
    async loadData() {
      try {
        await Promise.all([
          this.fetchServers(),
          this.fetchTasks(),
          this.fetchLogs(),
          this.fetchUsers()
        ])
        
        // 更新用户统计数据
        const stats = this.$store.state.users.stats || {}
        this.userStats.totalUsers = stats.totalUsers || 0
        this.userStats.onlineUsers = stats.onlineUsers || 0
        this.userStats.newUsers = stats.newUsers || 0
        
        this.$nextTick(() => {
          this.updateCharts()
        })
      } catch (error) {
        this.$message.error('加载数据失败: ' + error.message)
      }
    },
    async refreshData() {
      await this.loadData()
      this.$message.success('数据刷新成功')
    },
    handleDateChange() {
      // 日期范围改变时的处理逻辑
      this.$message.info('日期范围已更新')
    },
    initCharts() {
      // 初始化图表
      this.statusChart = echarts.init(this.$refs.statusChart)
      this.osChart = echarts.init(this.$refs.osChart)
      this.trendChart = echarts.init(this.$refs.trendChart)
      this.userGrowthChart = echarts.init(this.$refs.userGrowthChart)
      
      // 设置图表初始状态
    },
    handleResize() {
      if (this.statusChart) {
        this.statusChart.resize()
      }
      if (this.osChart) {
        this.osChart.resize()
      }
      if (this.trendChart) {
        this.trendChart.resize()
      }
      if (this.userGrowthChart) {
        this.userGrowthChart.resize()
      }
    },
    setChartOptions() {
      // 设置状态图表选项
      this.statusChart.setOption({
        title: {
          text: '迁移任务状态',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '状态',
            type: 'pie',
            radius: '50%',
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
      
      // 设置操作系统图表选项
      this.osChart.setOption({
        title: {
          text: '服务器操作系统分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '操作系统',
            type: 'pie',
            radius: ['40%', '70%'],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
      
      // 设置趋势图表选项
      this.trendChart.setOption({
        title: {
          text: '迁移任务趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '任务数',
            type: 'line',
            data: [],
            smooth: true
          }
        ]
      })
      
      // 设置用户增长趋势图表选项
      this.userGrowthChart.setOption({
        title: {
          text: '用户增长趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '用户数',
            type: 'line',
            data: [],
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: '#409EFF20'
            }
          }
        ]
      })
    },
    updateCharts() {
      // 更新任务状态图表
      if (this.statusChart) {
        const statusData = [
          { value: this.taskList.filter(t => t.status === 'COMPLETED').length, name: '已完成' },
          { value: this.taskList.filter(t => t.status === 'RUNNING').length, name: '运行中' },
          { value: this.taskList.filter(t => t.status === 'FAILED').length, name: '失败' },
          { value: this.taskList.filter(t => t.status === 'PENDING').length, name: '待处理' }
        ]
        
        this.statusChart.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            bottom: '0%',
            left: 'center'
          },
          series: [
            {
              name: '任务状态',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: statusData
            }
          ]
        })
      }
      
      // 更新操作系统分布图表
      if (this.osChart) {
        const osStats = {}
        this.serverList.forEach(server => {
          const os = server.os || '未知'
          osStats[os] = (osStats[os] || 0) + 1
        })
        
        const osData = Object.keys(osStats).map(os => ({
          name: os,
          value: osStats[os]
        }))
        
        this.osChart.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            bottom: '0%',
            left: 'center'
          },
          series: [
            {
              name: '操作系统',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: osData
            }
          ]
        })
      }
      
      // 更新迁移任务趋势图表
      if (this.trendChart) {
        // 生成最近7天的数据
        const dates = []
        const taskCounts = []
        const now = new Date()
        
        for (let i = 6; i >= 0; i--) {
          const date = new Date(now)
          date.setDate(date.getDate() - i)
          const dateStr = date.toISOString().slice(0, 10)
          dates.push(dateStr)
          
          // 计算当天创建的任务数
          const count = this.taskList.filter(task => {
            if (!task.createdAt) return false
            const taskDate = new Date(task.createdAt)
            return taskDate.toISOString().slice(0, 10) === dateStr
          }).length
          
          taskCounts.push(count)
        }
        
        this.trendChart.setOption({
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: dates
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: taskCounts,
            type: 'line',
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: '#409EFF20'
            }
          }]
        })
      }
      
      // 更新用户增长趋势图表
      if (this.userGrowthChart) {
        // 生成最近7天的数据
        const dates = []
        const userCounts = []
        const now = new Date()
        
        for (let i = 6; i >= 0; i--) {
          const date = new Date(now)
          date.setDate(date.getDate() - i)
          const dateStr = date.toISOString().slice(0, 10)
          dates.push(dateStr)
          
          // 计算当天注册的用户数
          const count = this.userList.filter(user => {
            if (!user.createdAt) return false
            const userDate = new Date(user.createdAt)
            return userDate.toISOString().slice(0, 10) === dateStr
          }).length
          
          userCounts.push(count)
        }
        
        this.userGrowthChart.setOption({
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: dates
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: userCounts,
            type: 'line',
            smooth: true,
            itemStyle: {
              color: '#67C23A'
            },
            areaStyle: {
              color: '#67C23A20'
            }
          }]
        })
      }
    }
  }
}
</script>

<style scoped>
.reports-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.stats-row {
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 10px;
  overflow: hidden;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stat-icon.primary {
  background: linear-gradient(135deg, #409EFF 0%, #64b5f6 100%);
}

.stat-icon.success {
  background: linear-gradient(135deg, #67C23A 0%, #81C784 100%);
}

.stat-icon.warning {
  background: linear-gradient(135deg, #E6A23C 0%, #FFB74D 100%);
}

.stat-icon.info {
  background: linear-gradient(135deg, #909399 0%, #A7A9AE 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.charts-row {
  margin-bottom: 30px;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
  font-size: 16px;
}

.chart-container {
  height: 400px;
  position: relative;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}

.chart-placeholder::before {
  content: "图表加载中...";
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .stats-row ::v-deep .el-col {
    margin-bottom: 15px;
  }
  
  .chart-container {
    height: 300px;
  }
}
</style>